package cc.eddic.pratice.programmingparadigms.nginxlog;

import cc.eddic.pratice.programmingparadigms.advanced.BeanFactory;
import cc.eddic.pratice.programmingparadigms.nginxlog.impl.LogItemParserZyzImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertNotNull;

@Slf4j
public class NginxLogTestZyz {
    private final TextFileReader textFileReader = BeanFactory.getBean(TextFileReader.class, "");
    private final NginxLogParser nginxLogParser = BeanFactory.getBean(NginxLogParser.class, "");
//    private final LogItemParser logItemParser = BeanFactory.getBean(LogItemParser.class);
    private final LogReport logReport = BeanFactory.getBean(LogReport.class);
    private final LogItemParser logItemParser = new LogItemParserZyzImpl();
    @Test
    public void pvUv() throws IOException {
        val data = nginxLogItemStream().collect(Collectors.toList());
        val report = logReport.pageViewsAndUniqueVisitors(data);
        assertNotNull(report);
    }


    @Test
    public void pvUvByHour() throws IOException, ParseException {
        val data = nginxLogItemStream().collect(Collectors.toList());
        val hourMap = logReport.pageViewsAndUniqueVisitorsByHour(data);
        assertNotNull(hourMap);
    }

    @Test
    public void pvUvByPath() throws IOException {
        val pathModelList = logReport.pageViewsAndUniqueVisitorsByPath(logItemList());
        assertNotNull(pathModelList);
    }




    private Stream<NginxLogItem> nginxLogItemStream() throws IOException {
        String fn = System.getenv("SONY_JAVA_PRACTICE_NGINX_LOG_FILE");
        if (log.isDebugEnabled()) log.debug("nginx log row count {}", textFileReader.read(fn).count());
        return textFileReader.read(fn).map(nginxLogParser::parse).filter(Optional::isPresent).map(Optional::get);
    }

    private List<LogItem> logItemList() throws IOException {
        return nginxLogItemStream()
                .map(logItemParser::parse).filter(Optional::isPresent).map(Optional::get)
                .collect(Collectors.toList());
    }
}
